<?php

namespace App\Http\Controllers\Web\Buyer;

use App\ConstDir\ErrorConst;
use App\Http\Controllers\Web\BaseController;
use App\Repository\Models\Carts;
use App\Repository\Models\UserInvoice;
use App\Repository\Repositories\Interfaces\CartsRepository;
use App\Repository\Repositories\Interfaces\InvoicesRepository;
use App\Repository\Repositories\Interfaces\ProductSkusRepository;
use App\Repository\Repositories\Interfaces\UserInvoiceRepository;
use Illuminate\Http\Request;

/**
 * 发票管理控制器
 *
 * @package App\Http\Controllers\Backend
 */
class UserInvoicesController extends BaseController
{
    /**
     * @var InvoicesRepository
     */
    protected $user_invoices_repo;

    protected $user_id;

    public function __construct(UserInvoiceRepository $user_invoices_repo)
    {
        parent::__construct();
        $this->user_invoices_repo = $user_invoices_repo;
        $this->user_id = array_get($this->user, 'id');
        //用户只能操作自身所属数据
        $this->user_invoices_repo->scopeQuery(function ($query) {
            return $query->where('user_id', $this->user_id);
        });
    }

    public function index(Request $request)
    {
        $this->validate($request, [
            'type' => 'in:page,all'
        ]);
        $type = $request->get('type', 'page');
        if($type == 'page'){
            $user_invoices = $this->user_invoices_repo->paginate($this->perPage);
            return $this->success(ErrorConst::SUCCESS_CODE, $user_invoices, true);
        }else{
            $user_invoices = $this->user_invoices_repo->all();
            return $this->success(ErrorConst::SUCCESS_CODE, $user_invoices['data']);
        }
    }

    public function show($id)
    {
        $user_invoice = $this->user_invoices_repo->find($id);
        return $this->success(ErrorConst::SUCCESS_CODE_MSG, $user_invoice['data']);
    }

    /**
     * 创建与更新共用
     * @param Request $request
     * @return \Illuminate\Support\Collection
     */
    public function store(Request $request)
    {
        $invoice_message = $request->get('invoice_message', 1);
        $invoice_type = $request->get('invoice_type', 1);
        // 当发票类型 是企业发票时，验证各条件。
        if ($invoice_message!=1) {
            $this->validate($request, [
                'id' => 'integer',
                'invoice_message' => 'required|integer|in:' . implode(',', array_keys(UserInvoice::$invoice_message_map)),
                'invoice_type' => 'required|integer|in:' . implode(',', array_keys(UserInvoice::$invoice_type_map)),
                'invoice_title' => 'required|string',
                'tax_code' => 'required_if:invoice_message,2|string',
                'invoice_address' => 'required_if:invoice_message,2|string',
                'invoice_tel' => 'required_if:invoice_message,2|string',
                'invoice_bank' => 'required_if:invoice_message,2|string',
                'invoice_account' => 'required_if:invoice_message,2|string',
                'post_address' => 'required_if:invoice_message,2|string',
                'post_contacts' => 'required_if:invoice_message,2|string',
                'post_tel' => 'required_if:invoice_message,2|string',
                'remark' => 'string',
            ], [
            ]);

            // $verifyFilter
            $verifyFilter = ['invoice_message'=> $invoice_message,'invoice_type'=>$invoice_type];
        }else{
            $this->validate($request, [
                'invoice_title' => 'required',
            ],
            [
                'invoice_title'=>'发票抬头不可为空',
            ]);

            // $verifyFilter
            $verifyFilter = ['invoice_message'=> $invoice_message];
        }
        $id = $request->get('id', null);

        //  个人发票 
        if ($invoice_message ==1) {
            $verifyFilter = ['invoice_message'=> $invoice_message];
        //  企业发票 
        }elseif($invoice_message ==2){
            $verifyFilter = ['invoice_message'=> $invoice_message,'invoice_type'=>$invoice_type];
        }
        $verifyExist = $this->user_invoices_repo->findWhere($verifyFilter);
        // 如果在添加的时候，且查询结果 大于 0 条记录，即返回错误
        if (count($verifyExist['data'])>0) {
            if (!is_null($id)) {
                $verifyExist = $this->user_invoices_repo->find($id);
                // 已存在 id 即更新的时候需要 验证是否是更改了类型。如果与查询结果。
                if (intval($invoice_message) != $verifyExist['data']['invoice_message']) {
                    return $this->error(ErrorConst::INVOICE_UPDATE_ERROR_MSG,ErrorConst::INVOICE_UPDATE_ERROR_CODE);
                }elseif (intval($invoice_message)==2 && ($invoice_type != $verifyExist['data']['invoice_type'])) {
                    return $this->error(ErrorConst::INVOICE_UPDATE_ERROR_MSG,ErrorConst::INVOICE_UPDATE_ERROR_CODE);
                }
            }else{
                return $this->error(ErrorConst::INVOICE_ADD_ERROR_MSG,ErrorConst::INVOICE_ERROR_CODE);
            }
        }

        $data = $request->all();
        $data['user_id'] = $this->user_id;
        $ret = $this->user_invoices_repo->updateOrCreate(['id' => $id], $data);

        return $this->noDataReturn($ret ? true : false);
    }

    /**
     * 设置默认项
     * @param Request $request
     */
    public function update($id)
    {
        $ret = $this->user_invoices_repo->setDefault($id);
        return $this->noDataReturn($ret ? true : false);
    }

    public function delete($id)
    {
        $ret = $this->user_invoices_repo->delete($id);
        return $this->noDataReturn($ret ? true : false);
    }
    /**
     * 检测是否可继续添加发票
     * @param Request $request
     */
    public function check()
    {
        $ret = $this->user_invoices_repo->checkInvoice();
        return $this->success(ErrorConst::SUCCESS_CODE_MSG, $ret);
//        return $this->noDataReturn($ret ? true : false);
    }
}
